package com.jfirer.validator.descriptor;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintDeclarationException;
import javax.validation.Valid;
import javax.validation.groups.ConvertGroup;
import javax.validation.groups.ConvertGroup.List;
import javax.validation.metadata.CascadableDescriptor;
import javax.validation.metadata.GroupConversionDescriptor;

public abstract class CascadableDescriptorImpl extends ElementDescriptorImpl implements CascadableDescriptor
{
	protected boolean							cascaded;
	protected Set<GroupConversionDescriptor>	groupConversions;
	
	protected void initializeCascadableDescriptor(boolean cascaded, Set<GroupConversionDescriptor> groupConversions)
	{
		this.cascaded = cascaded;
		this.groupConversions = groupConversions;
	}
	
	@Override
	public boolean isCascaded()
	{
		return cascaded;
	}
	
	@Override
	public Set<GroupConversionDescriptor> getGroupConversions()
	{
		return groupConversions;
	}
	
	protected boolean defineCascaded(Annotation... annotations)
	{
		for (Annotation annotation : annotations)
		{
			if (annotation.annotationType() == Valid.class)
			{
				return true;
			}
		}
		return false;
	}
	
	protected Set<GroupConversionDescriptor> defineGroupConversions(Annotation... annotations)
	{
		boolean isValid = false;
		Set<GroupConversionDescriptor> set = new HashSet<GroupConversionDescriptor>();
		for (Annotation annotation : annotations)
		{
			if (annotation.annotationType() == Valid.class)
			{
				isValid = true;
				continue;
			}
			if (annotation.annotationType() == ConvertGroup.class)
			{
				set.add(new GroupConversionDescriptorImpl((ConvertGroup) annotation));
			}
			else if (annotation.annotationType() == ConvertGroup.List.class)
			{
				ConvertGroup.List list = (List) annotation;
				for (ConvertGroup convertGroup : list.value())
				{
					set.add(new GroupConversionDescriptorImpl(convertGroup));
				}
			}
		}
		if (isValid == false && set.isEmpty() == false)
		{
			throw new ConstraintDeclarationException("非法定义，使用ConvertGroup的地方没有Valid注解");
		}
		return set;
	}
}
